#include "my_stdio.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include<string.h>
#include <fcntl.h>

my_FILE * myopen(const char * filename ,const char* mode)
{
    int fd=0;
    if(strcmp(mode,"w")==0)
    {
       fd= open(filename,O_WRONLY|O_CREAT,0666);
       if(fd==-1)
       {
           perror("open file is error\n");
           return NULL;
       }
    }
    else if(strcmp(mode,"r")==0)
    {
        
        fd= open(filename,O_RDONLY);
       if(fd==-1)
       {
           perror("open file is error\n");
           return NULL;
       }
    }
    else{
        perror("mode is error\n");
        return NULL;
    }

    my_FILE* file=(my_FILE*)malloc(sizeof(my_FILE));
    file->size=0;
    file->capcity=SIZE;
    file->filenumber=fd;
    file->flag=AFLUSH;
    return file;
}

 int myfwrite(const char *ptr,int num,my_FILE* stream)
{
    //这里需要注意，防止数据丢失
  //  while(stream->size+num>=stream->capcity)
  //  {
  //      //缓冲区满，需要刷新缓存区
  //      myfflush(stream);
  //  }
    strncpy(stream->outbuffer+stream->size,ptr,num);

    stream->size+=num;

    if(stream->flag==NFLUSH)
    {
        myfflush(stream);
        stream->size=0;
    }
    else if(stream->flag==LFLUSH)
    {
        if(*(ptr+num-1)=='\n')
        {
            myfflush(stream);
        }
    }

    return num;
}

void myfflush(my_FILE* stream)
{
    write(stream->filenumber,stream->outbuffer,stream->size);
    stream->size=0;
}

void myclose(my_FILE* file)
{
    myfflush(file);
    close(file->filenumber);
    free(file);

}

